package com.person.jc.service.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.person.jc.entity.TsUser;
import com.person.jc.utils.Utils;

public class TsVisitLogService {

	public static final TsVisitLogService me = new TsVisitLogService();
	
	public List<Record> getList(Map<String,Object> map){
		String temp = "";
		List<Object> params = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer(
				"select v.user_id,\n " +
				"v.user_name,\n" +
				"v.dept_name, \n" +
				"(case when v.login_ip <> '0:0:0:0:0:0:0:1' then v.login_ip else '127.0.0.1' end) login_ip,\n" + 
				"DATE_FORMAT(v.login_date,'%Y-%m-%d %T') login_date,\n" + 
				"DATE_FORMAT(v.logout_date,'%Y-%m-%d %T') logout_date\n" + 
				"from ts_visit_log v,ts_user u\n" +
				"where 1=1 and  u.user_id = v.user_id\n");
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("userId")))){
			sql.append(" and u.user_id like ?");
			params.add("%"+temp+"%");
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("userName")))){
			sql.append(" and u.user_name like ?");
			params.add("%"+temp+"%");
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("startDate")))){
			sql.append(" and DATE_FORMAT(v.login_date,'%Y-%m-%d') >= ?");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("endDate")))){
			sql.append(" and DATE_FORMAT(v.login_date,'%Y-%m-%d') <= ?");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("deptId")))){
			sql.append(" and u.dept_id = ?");
			params.add(temp);
		}
		
		sql.append(" order by v.login_date desc");
		return Db.find(sql.toString(), Utils.getObjParam(params));
	}
	
	public void saveLoginInfo(TsUser tsUser, String loginIp, Serializable sessionId){
        try {
            String sql = 
            	"insert into ts_visit_log\n" +
            	"  (log_id, user_id, user_name, dept_id, dept_name, login_date, login_ip)\n" + 
            	"values\n" + 
            	"  (?, ?, ?, ?, ?, now(), ?)";

            Object[] obj = new Object[6];
            obj[0] = sessionId;
            obj[1] = tsUser.getUserId();
            obj[2] = tsUser.getUserName();
            obj[3] = tsUser.getDeptId();
            obj[4] = tsUser.getDeptName();
            obj[5] = loginIp;
            Db.update(sql, obj);
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }
    
    public void updateLoginInfo(Serializable sessionId){
        try {
            String sql = "update ts_visit_log set logout_date = now() where log_id = ?";
            Object[] obj = new Object[1];
            obj[0] = sessionId;
            
            Db.update(sql, obj);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
